package com.jch.dm.chapter_21_proxy;

/**
 * @author: Administrator
 * @create: 2020/04/12 11:24
 **/
public class PrinterProxy implements Printable {

    /**
     * 名字
     */
    private String name;
    /**
     * 被代理者
     */
    private Printer real;

    public PrinterProxy() {
    }

    public PrinterProxy(String name) {
        this.name = name;
    }

    /**
     * 设置名称
     *
     * @param name
     */
    @Override
    public synchronized void setPrinterName(String name) {
        if (real != null) {
            real.setPrinterName(name);
        }
        this.name = name;
    }

    /**
     * 获取名称
     *
     * @return name
     */
    @Override
    public String getPrinterName() {
        return name;
    }

    /**
     * 显示文字（打印输出）
     *
     * @param string
     */
    @Override
    public void print(String string) {
        realize();
        real.print(string);
    }

    /**
     * 生成被代理者
     */
    private synchronized void realize() {
        if (real == null){
            real = new Printer(name);
        }
    }
}
